package com.learning.repository.impl;

import java.lang.reflect.ParameterizedType;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.learning.repository.IBaseRepository;

@SuppressWarnings("unchecked")
public abstract class GenericRepository<T,ID> implements IBaseRepository<T, ID> {

	  
		@PersistenceContext(unitName="LearningUP")
		protected EntityManager em;
		 private Class<T> entityClass;
		// private Class<ID> privateKeyClass;
		 
		 
		 public GenericRepository() {
				super();
				this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
				  //  this.privateKeyClass = (Class<ID>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
					   
			}
		 
	@Override
	public T findById(Long id) {
		 Object obj = em.find(entityClass, id);
	        if (obj == null)
	            return null;
	        return (T) obj;
	}

	

	@Override
	public T insert(T o) {
		em.persist(o);
		return o;
	}

	@Override
	public T update(T o) {
		o=em.merge(o);
		  return o;	
	}

	@Override
	public T delete(T o) {
		em.remove(em.merge(o));
		return o;
	}

	@Override
	public List<T> findAll() {
		List<T> Ts = new ArrayList<>();
		TypedQuery<T> query = em.createNamedQuery(entityClass.getSimpleName()+".findAll", entityClass);
		Ts = query.getResultList();

		return Ts;
	}

}
